const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabIndex: 0,
    info: null,
    shop_info: null,
    src: [],
    navigator: { hide: 0 },
    need: {
      days: 0,
      hours: 0,
      minutes: 0,
      second: 0
    },
    options:null,
    fenxiangzhuan: {
      show: false,
      width: '86rpx;',
      height: '88rpx;',
      bottom: '360rpx;',
      top: '10rpx'
    }
  },
  jump:function(){
    wx.navigateTo({
      url: '/pages/shop/tccar/tccar',
    })
  },
  //快捷导航
  navigator: function (e) {
    var width = this.data.navigator.width
    if (this.data.navigator.hide == 1) {
      var offset = '0'
      var mum = 0;
    } else {
      var offset = width * 0.64
      var mum = 1;
    }
    this.animation.translateX(offset).step()
    var v = this.data.navigator
    v.animation = this.animation.export();
    v.hide = mum;
    this.setData({
      //输出动画
      navigator: v
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    wx.showLoading({
      title: '加载中…',
    })
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    this.setData({
      token: extConfig.appid
    })
    let that = this;
    //快速导航
    app.ihttpGet("https://www.58zltc.com/api.php/Index/getNav", function (res) {
      var v = that.data.navigator;
      v.info = res.data
      that.setData({
        navigator: v
      })
    })
    //屏幕宽度
    wx.getSystemInfo({
      success: function (res) {
        var width = res.screenWidth;
        var v = that.data.navigator;
        v.width = width
        that.setData({
          navigator: v
        })
      },
    })

    //实例化一个动画
    this.animation = wx.createAnimation({
      // 动画持续时间，单位ms，默认值 400
      duration: 300,
      /**
       * linear 动画一直较为均匀
       * ease  从匀速到加速在到匀速
       * ease-in 缓慢到匀速
       * ease-in-out 从缓慢到匀速再到缓慢
       * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
       * step-end  保持 0% 的样式直到动画持续时间结束    一闪而过
       */
      timingFunction: 'ease',
      // 延迟多长时间开始
      delay: 100,
      /**
       * 以什么为基点做动画 效果自己演示
       * left,center right是水平方向取值，对应的百分值为left=0%;center=50%;right=100%
       * top center bottom是垂直方向的取值，其中top=0%;center=50%;bottom=100%
       */
      transformOrigin: 'right',
      success: function (res) {

      }
    })
    var width = this.data.navigator.width;
    var offset = width * 0.64;
    that.animation.translateX(offset).step()
    var v = this.data.navigator
    v.animation = that.animation.export()
    v.hide = 1
    that.setData({
      //输出动画
      navigator: v
    })
    //ver-jionEndTime
    app.ihttpGet('https://www.58zltc.com/api.php/Goods/verJionEndTime/id/' + options.id, function (res) {
      that.setData({
        verJoinEndTime: res.data
      })
    })
    if(options.type){
      var url = 'https://www.58zltc.com/api.php/Goods/item/type/' + options.type + '/id/' + options.id + '/openid/' + options.openid + '/kan_openid/' + app.globalData.openid;
    }else{
      var url = 'https://www.58zltc.com/api.php/Goods/item/openid/' + app.globalData.openid+'/id/' + options.id
    }
    that.setData({
      options: options
      })
  //console.log(this.data.options);
    app.ihttpGet(url, function(res){
      
      var WxParse = require('../../../wxParse/wxParse.js');
      var article = res.data.content;
      WxParse.wxParse('article', 'html', article, that, 5);

      that.setData({
        info: res.data,
        kan_openid: app.globalData.openid,
        openid: options.openid
      })
      if (res.data.is_qiang == 1 && res.data.qiang_time != 2) {
        that.setCountdown();
      }
      that.setShopInfo(res.data.shop_id);
    })
  },
  setCountdown: function(){
    let that = this;
    var d_minutes, d_hours, d_days, d;
    var timeNow = parseInt(new Date().getTime() / 1000);
    var data = this.data.info;
    if(data.qiang_time == 0){
      var pTime = data.start_date+' '+data.start_time;
    } else if (data.qiang_time == 1){
      var pTime = data.end_date + ' ' + data.end_time;
    }
    pTime = pTime.replace(/-/g, '/');
    var pTime_new = new Date(pTime).getTime() / 1000;
    d = Math.abs(timeNow - pTime_new);

    var need = {};
    need.days = parseInt(d / 86400);
    d = d % 86400;
    need.hours = parseInt(d / 3600);
    d = d % 3600;
    need.minutes = parseInt(d / 60);
    need.second = d % 60;
    this.setData({
      need:need
    })
    setTimeout(function(){
      that.setCountdown();
    }, 1000);
  },
  setTab: function (e) {
    this.setData({
      tabIndex: e.currentTarget.dataset.id
    })
  },
  setShopInfo: function (shop_id){
    let that = this;
    app.ihttpGet('https://www.58zltc.com/api.php/Shop/item/shop_id/' + shop_id, function(res){
      that.setData({
        shop_info: res.data
      })
    })
  },
  kan: function(e){
    var that1 = this;
    app.ihttpGet('https://www.58zltc.com/api.php/Goods/addKanLog/type/kan/id/' + this.data.info.id + '/openid/' + this.data.openid + '/kan_openid/' + this.data.kan_openid, function (res) {
      app.iModel(res.data.err_msg);
      var options = that1.data.options;
      wx.showLoading({
        title: '加载中…',
      })
      let that = that1;
      if (options.type) {
        var url = 'https://www.58zltc.com/api.php/Goods/item/type/' + options.type + '/id/' + options.id + '/openid/' + options.openid + '/kan_openid/' + app.globalData.openid;
      } else {
        var url = 'https://www.58zltc.com/api.php/Goods/item/openid/' + app.globalData.openid + '/id/' + options.id
      }

      app.ihttpGet(url, function (res) {
        that.setData({
          info: res.data,
          kan_openid: app.globalData.openid,
          openid: options.openid
        })
        if (res.data.is_qiang == 1 && res.data.qiang_time != 2) {
          that.setCountdown();
        }
        that.setShopInfo(res.data.shop_id);
        wx.setNavigationBarTitle({
          title: res.data.title,
        })
      })
      })
      
  },
  longtap: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.src;
    this.data.src.push(url);
    wx.previewImage({
      urls: that.data.src
    })
  },
  submitInfo:function(e){
    var t =this;
    var type = e.detail.target.dataset.type;
    var formid = e.detail.formId;
    app.ihttpPost("https://www.58zltc.com/api.php/Index/addFormId", { form_id: formid, openid: app.globalData.openid }, function (res) { })
    this.setData({
      type:type
    })
    t.pay();
  },
  pay: function(e){
    console.log(e)
    if (typeof(e) !='undefined'){
      var order_type = e.currentTarget.dataset.type;
    }else{
      var order_type = this.data.type;
    }
    var post_data = {};
    post_data.id = this.data.info.id;
    // var url = '/pages/shop/pintuan/share?id=' + this.data.info.tuan_first_id;
    // wx.navigateTo({
    //   url: url,
    // })
    post_data.openid = app.globalData.openid;
    if (order_type){
      post_data.type = order_type;
    }

    app.ihttpPost("https://www.58zltc.com/api.php/Goods/addGoodsOrder", post_data, function(res){
      if (res.data.err_code == 400) {
        app.iModel(res.data.err_msg);
      } else {
        var data = res.data;
        var prepay_id  = res.data.package;
        var a = prepay_id.slice(10)
        wx.requestPayment({
          'appId': data.appId,
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paySign,
          'success': res => {
            //支付添加formid
            app.ihttpPost("https://www.58zltc.com/api.php/Index/addFormId", { form_id: a, openid: app.globalData.openid, type: 'pay' }, function (res) { })
            if (res.errMsg == 'requestPayment:ok') {
              if(order_type == 'pin'){
                var url = '/pages/shop/pintuan/share';
              }else{
                var url = '/pages/mine/order/order';
              }
              wx.navigateTo({
                url: url,
              })
            }
          }
        })
      }
    })
  },
  goShop: function () {
    let that = this;
    var shop_type = this.data.shop_info.type;
    var shop_url = '';
    if (shop_type == 'jiancai') {
      shop_url = '/pages/shop/jiancai/detail?shop_id=' + that.data.info.shop_id;
    } else if (shop_type == 'car') {
      shop_url = '/pages/shop/car/detail?shop_id=' + that.data.info.shop_id;
    } else if (shop_type == 'jiaoyu') {
      shop_url = '/pages/shop/jiaoyu/detail?shop_id=' + that.data.info.shop_id;
    } else {
      shop_url = '../detail?shop_id=' + that.data.info.shop_id;
    }
    wx.navigateTo({
      url: shop_url,
    })
  },
  goPintuan: function(e){
    wx.navigateTo({
      url: '/pages/shop/pintuan/share?id=' + e.currentTarget.dataset.id,
    })
  },
  bindCall: function () {
    var tel = this.data.shop_info.tel;
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.confirmCommission()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var options = this.data.options;
    //console.log(options);
    wx.showLoading({
      title: '加载中…',
    })
    let that = this;
    if (options.type) {
      var url = 'https://www.58zltc.com/api.php/Goods/item/type/' + options.type + '/id/' + options.id + '/openid/' + options.openid + '/kan_openid/' + app.globalData.openid;
    } else {
      var url = 'https://www.58zltc.com/api.php/Goods/item/openid/' + app.globalData.openid + '/id/' + options.id
    }

    app.ihttpGet(url, function (res) {
      that.setData({
        info: res.data,
        kan_openid: app.globalData.openid,
        openid: options.openid
      })
      if (res.data.is_qiang == 1 && res.data.qiang_time != 2) {
        that.setCountdown();
      }
      that.setShopInfo(res.data.shop_id);
      wx.setNavigationBarTitle({
        title: res.data.title,
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if(this.data.info.is_kan == 1){
      let that = this;
      return {
        title: '我正在参加' + this.data.info.title+'砍价活动！',
        path: '/pages/shop/goods/detail?type=kan&openid=' + app.globalData.openid + '&id=' + this.data.info.id + '&fenxiang=' + app.globalData.openid + '&fWid=' + that.data.shop_info.wid,
        success: function (res) {
          var a = that.data.fenxiangzhuan
          a.show = false
          that.setData({
            fenxiangzhuan: a
          })
          app.ihttpGet("https://www.58zltc.com/api.php/Goods/addKanLog/openid/" + app.globalData.openid + "/id/" + that.data.info.id, function(res){

          })
          // 转发成功
          wx.showToast({
            title: '转发成功！',
          })
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  },
  changeFXZ: function () {
    var that = this;
    var a = that.data.fenxiangzhuan
    a.show ? a.show = false : a.show = true
    that.setData({
      fenxiangzhuan: a
    })
  },
  //海报
  qrcode: function (e) {
    var that = this
    that.changeFXZ()
    wx.showLoading({
      title: '拼命生成中',
    })

    wx.request({
      url: 'https://www.58zltc.com/api.php/Qrcode/getGoodsPoster/goods_id/' + that.data.options.id + '/token/' + that.data.token,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        var url = res.data.data.url;
        var urls = [];
        urls.push(url);
        //获取用户授权状态
        wx.getSetting({
          success: (res) => {
            wx.hideLoading();
            if (res.authSetting["scope.writePhotosAlbum"]) {
              that.saveImg(url)
            } else {
              //授权
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  that.saveImg(url)
                },
                fail() {
                  wx.showModal({
                    title: '提示',
                    content: '自动保存未授权,请长按保存海报',
                    showCancel: false,
                    success: function (res) {
                      wx.previewImage({
                        urls: urls
                      })
                    }
                  })
                }
              })
            }
          }
        })
      },
      fail: function (e) {
        wx.hideLoading();
      }
    })
  },
  //保存图片到相册
  saveImg: function (url) {
    //保存海报
    var img_path
    wx.getImageInfo({
      src: url,
      success: function (res) {
        img_path = res.path
        wx.saveImageToPhotosAlbum({
          filePath: img_path,
          success(res) {
            wx.showToast({
              title: '已经保存至本地',
              duration: 2000
            })
          }
        })
      }
    })
  }
})